import React, {useEffect, useState} from "react";
import '../styles/style.css'
import FormHeader from "./FormHeader";
import Form from "./Form";
import OtherMethods from "./OtherMethods";
import {config} from "../../../config";
import {message} from "antd";
import {getUsersNamePromise, loginPromise} from "../../../api";
function LoginForm() {
    const [username, setUsername] = useState("")
    const [password, setPassword] = useState("")
    const changeUsername = (v) => setUsername(v)
    const changePwd = (v) => setPassword(v)
    let sender = {name: username, x:0, y:0}
    let clearFlag = false
    const login = () => {
        const api = `${config.baseUrl}getUsersName`
        getUsersNamePromise().then(res => {
            res = JSON.parse(res)
            console.log(res)
            if (res.code === 200) {
                for (let re of res.data) {
                    if (re === username) {
                        message.error("该用户已在线，请换个名称试试。")
                        return
                    }
                }
               window.location.href = "http://localhost:3000/chat/" + username
            }
        })
        // fetch(api, {method:"GET"}).then(res => {
        //     const data = res.text();
        //     data.then(res => {
        //         res = JSON.parse(res)
        //         console.log(res)
        //         if (res.code === 200) {
        //             for (let re of res.data) {
        //                 if (re === username) {
        //                     message.error("该用户已在线，请换个名称试试。")
        //                     return
        //                 }
        //             }
        //             window.location.href = "http://localhost:3000/chat/" + username
        //         }
        //     })
        //
        // })
    }

    // mounted hook
    useEffect(() => {
    }, [])

    // updated hook
    useEffect(()=>{
        if (!sender.name.trim().length) {
            clearFlag = true
        }
        console.log(sender)
        console.log(clearFlag)
        console.log(username)
    })

    useEffect(()=>{
        console.log(username)
    },[username])


    // beforeDestroy
    useEffect(()=> {
        return (
            ()=> {
                console.log("beforeDestroy")
            }
        )
    },[])

    return (
        <div id="loginform">
            <FormHeader title="探花app">
            </FormHeader>
            <Form clearFlag={clearFlag} changeUsername={changeUsername} changePwd={changePwd} login={login}>
            </Form>
            <OtherMethods>
            </OtherMethods>
        </div>
    );
}

export default LoginForm;
